<?php

namespace app\queue\event;

use app\queue\BaseConsumer;
use common\service\EventLogService;
use support\bootstrap\Redis;

class EventConsumer extends BaseConsumer
{

    // 要消费的队列名
    public $queue = 'event';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * 处理事件
     * @param $data
     */
    public function doConsume($data)
    {
        try {
            $key = $data['event_data_key'];

            // 记录 Event log 数据
            $eventLogService = new EventLogService();

            $now = time();
            $records = [];
            $index = 0;
            while (Redis::lLen($key) > 0) {

                $r = Redis::lPop($key);
                if (!empty($r)) {
                    $records[] = json_decode($r, true);
                }

                // 分片执行 避免内存不够
                if (count($records) >= 100 || (Redis::lLen($key) == 0 && count($records) > 0)) {
                    try {
                        $eventLogService->create($records);
                    } catch (\Throwable $e) {
                        trace(format_exception_info($e), 'ERR');
                    }

                    $index += count($records);
                    $records = [];
                }
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
